//获取应用实例
const app = getApp();
const quote = app.globalData.quote;
const path = quote.paths;
const util = require('../../../../utils/util.js');
const tools = require('../../../../utils/tools.js');
const api = require('../../../../utils/api.js');
const Authorize = quote.Authorize;
const recorder = app.globalData.recorder; //引入录音对象
const innerAudioContext = app.globalData.innerAudioContext; //引入音频播放器
Page({
    data: {
        userInfo: {},
        hasUserInfo: false,
        VID: null,//练习语句id
        recordFilePath: null,//临时录音文件地址
        canIUse: wx.canIUse('button.open-type.getUserInfo'),
        loginStatus: false,
        PracticeSentence: null,
        isRecord: false,//是否正在录音
        isPlaying: false,//是否正在播放示例录音
        isRecordPlaying: false,//是否正在播放用户录音
        isButtonClick: false,//是否有按钮被点击
        isRecordClick: false,//是否录音按钮被点击
        recordEnd: false,//录音完成

        timeToplimit: 60,//录音时间上限
        timeLowerlimit: 1,//录音时间下限
        remainingTime: 60,//录音剩余时间
        timeKeeping: 0,//录音计时时间
        voiceDuration: 0,//录音时长
        remain: 0,//播放录音剩余时间
        playtimeKeeping: 0,//播放录音计时
        playRecordText: "00:00",//播放录音时长时间格式化
        timeKeepingText: "00:00",//录音计时时长时间格式化

        result: null,//录音结果
        score: null, //录音得分
        integrity: null, //完整度
        rhythm: null, //节律度
        pronunciation: null, //发音得分
        voiceText: null, //用户得分文本

        slideAnimate: false, //滑入滑出动画
        sentence: '.', //不为空是为了防止dispose方法中报出一个不影响结果的报错
        wordList: null, //句子拆分成的单词数组
        currentWord: null,//当前选中单词下标
        wordResult: null,//单词查询结果
        scrollTop: null, //单词查询滚动条位置

        maskTips: true,//新版功能提示
        isIndex: true, //是否还在首页
        hidePop:true
    },
    onLoad(options) {
        let _self = this;
        if (app.globalData.userInfo) {
            this.setData({
                userInfo: app.globalData.userInfo,
                hasUserInfo: true
            })
        } else if (this.data.canIUse) {
            // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
            // 所以此处加入 callback 以防止这种情况
            app.userInfoReadyCallback = res => {
                this.setData({
                    userInfo: res.userInfo,
                    hasUserInfo: true
                })
            }
        } else {
            // 在没有 open-type=getUserInfo 版本的兼容处理
            wx.getUserInfo({
                success: res => {
                    app.globalData.userInfo = res.userInfo
                    this.setData({
                        userInfo: res.userInfo,
                        hasUserInfo: true
                    })
                }
            })
        }
        console.log(app.globalData.userInfo)
        wx.showLoading({
            title: '加载中',
        })
        if (options.hasOwnProperty('VID')) {
            console.log("查找指定句子")
            this.setData({
                VID: options.VID
            })
            this.assignSentence();
        } else {
            console.log("随机加载句子")
            this.indexSentence();
        }
        this.dispose();
        // 判断是否显示新版功能提示
        wx.getStorage({
            key: 'maskTips',
            success: (res) => {
                _self.setData({
                    maskTips: true
                })
            },
            fail: (res) => {
                _self.setData({
                    maskTips: false
                })
            },
            complete: (res) => {
            }
        })
    },
    onReady() {
        let _self = this;
      // app.getUserInfo()
        //延迟检验用户信息授权，避免和系统自带提示授权冲突
        // setTimeout(function () {
        //     app.checkImpower()
        // }, 4000)
        app.checkRecord()
        // 监听加速度计
        // wx.onAccelerometerChange(function(res) {
        //     if(_self.data.isIndex){
        //         if(res.x>2||res.y>2||res.z>2){
        //             console.log("触发摇一摇")
        //             _self.randomSentence();
        //             wx.vibrateLong()
        //         }
        //     }
			
        // })
    },
    onShow() {
        let _self = this;
        _self.setData({
          hidePop: true
        })
      
        // 开始监听加速度计
        // wx.startAccelerometer()
        // _self.setData({
        //     isIndex: true,
        // })
    },
    onHide () {
        var _self = this;
       
        recorder.cancel({
            //取消录音完成回调
            onStop: function (ret) {
                console.log("手动返回取消了录音：", ret)
            }
        });
        innerAudioContext.stop();
        clearInterval(_self.timer);
        if (!_self.data.recordEnd) {
            _self.setData({
                isRecord: false,
                isPlaying: false,
                isRecordPlaying: false,
                recordEnd: false,
                isRecordClick: false,
                timeKeepingText: "00:00",
            })
        }else{
            _self.setData({
                isRecord: false,
                isPlaying: false,
                isRecordPlaying: false,
                isRecordClick: false,
                timeKeepingText: "00:00",
            })
        }
        // 停止监听加速度计
        // wx.stopAccelerometer();
        // _self.setData({
        //     isIndex: false
        // })
        
    },
    onUnload(){
      var _self = this;
      _self.recordEnd()
      recorder.cancel({
        //取消录音完成回调
        onStop: function (ret) {
          console.log("手动返回取消了录音：", ret)
        }
      });
    },
    // 获取首页练习语句
    indexSentence() {
        console.log('准备获取首页数据');
        let _self = this;
        api.methodGetIndexPracticeSentence({
            dataDic: {},
            success: (res) => {
                console.log("首页句子数据", res);
                res.data.data.PracticeSentence.ImgUrl = app.globalData.mediaUrl + res.data.data.PracticeSentence.ImgUrl;
                res.data.data.PracticeSentence.SentenceVoice = app.globalData.mediaUrl + res.data.data.PracticeSentence.SentenceVoice;
                _self.setData({
                    PracticeSentence: res.data.data.PracticeSentence,
                    VID: res.data.data.PracticeSentence.VID,
                    sentence: res.data.data.PracticeSentence.SentenceEn
                })
                _self.dispose()
                wx.hideLoading()
            },
            fail: (res) => {
                console.log('失败', res);
            },
            complete: (res) => {
                console.log('完成', res.data);
            }
        })
    },
    //获取指定练习语句
    assignSentence() {
        let _self = this;
        let dataDic = {
            PID: _self.data.VID
        };
        api.methodGetAssignPracticeSentence({
            dataDic,
            success: (res) => {
                console.log("指定句子数据", res);
                res.data.data.PracticeSentence.ImgUrl = app.globalData.mediaUrl + res.data.data.PracticeSentence.ImgUrl;
                res.data.data.PracticeSentence.SentenceVoice = app.globalData.mediaUrl + res.data.data.PracticeSentence.SentenceVoice;
                _self.setData({
                    PracticeSentence: res.data.data.PracticeSentence,
                    VID: res.data.data.PracticeSentence.VID,
                    sentence: res.data.data.PracticeSentence.SentenceEn
                })
                wx.hideLoading()
                _self.dispose()
            },
            fail: (res) => {
                console.log(res);
            },
            complete: (res) => {
                console.log(res.data);
            }
        })

    },
    //随机切换练习语句
    randomSentence() {
        app.aldstat.sendEvent('练口语-点击换一换');
        let _self = this;
        innerAudioContext.stop();
        api.methodGetIndexPracticeSentence({
            dataDic: {},
            success: (res) => {
                console.log("随机句子数据", res);
                res.data.data.PracticeSentence.ImgUrl = app.globalData.mediaUrl + res.data.data.PracticeSentence.ImgUrl;
                res.data.data.PracticeSentence.SentenceVoice = app.globalData.mediaUrl + res.data.data.PracticeSentence.SentenceVoice;
                _self.setData({
                    PracticeSentence: res.data.data.PracticeSentence,
                    VID: res.data.data.PracticeSentence.VID,
                    sentence: res.data.data.PracticeSentence.SentenceEn,
                    isPlaying: false,
                    isRecord: false,
                    isRecordPlaying: false,
                    isButtonClick: false,
                    isRecordClick: false,
                    recordEnd: false,
                })
                _self.dispose()
            },
            fail: (res) => {
                console.log(res);
            },
            complete: (res) => {
                console.log(res.data);
            }
        })
    },

  //去下一页
  getuserinfo(params) {
    var that = this
    console.log('点击下一页', params);
    var userObj = params.detail;
    var getUserInfo = userObj.errMsg.split(':');
    if (getUserInfo[1] != 'ok') {
      console.log(11)
      Authorize.checkUserInfo(function (res) {
        if (!res) {
          that.setData({
            hidePop: false
          })
        } else {
          that.setData({
            hidePop: true
          })
        }
      }) //进入授权流程
      return
    } else {
      console.log(22)
      app.globalData.userInfo = userObj.userInfo; //用户信息存入全局
      wx.setStorage({
        key: 'userInfo',
        data: userObj.userInfo,
        success: function (res) {
          console.log('用户信息存入缓存成功', res)
        }
      })
      that.recordStart()
    }

  },


    //开始录音
    recordStart() {
      // app.getUserInfo()
      // app.checkImpower()
        
        this.startLearning();
        innerAudioContext.stop();
        let _self = this;
        if (_self.data.isRecordClick) {
            console.log("录音按钮被点击，请稍后再点")
            return
        }
        if(parseInt(_self.data.score)>0){
            app.aldstat.sendEvent('练口语-点击重新练习');
        }else{
            app.aldstat.sendEvent('练口语-点击录音');
        }
        //录音提交参数
        let scoreCfg = {
            coreType: 'sent.eval', //测评类型 
            refText: _self.data.PracticeSentence.SentenceEn, //参考文本 
            scale: 100, //分制 
            precision: 1, //精度 
            dict_type: 'kk', //音素字典选项  
            slack: 0 //宽松度 
        }
        wx.showLoading({
            title: '准备录音中'
        })
        
        recorder.start({
            duration: 60 * 1000, //录音时长  
            serverParams: scoreCfg, //录音传参
            //开始录音成功回调
            onStart() {
                wx.hideLoading()
                console.log("录音开始onStart");
                _self.setData({
                    isRecord: true,
                    isRecordClick: true,
                    isPlaying: false,
                    isRecordPlaying: false,
                    timeKeeping: 0
                });
                clearInterval(_self.timer);
                let timer = setInterval(function () {
                    _self.setData({
                        timeKeeping: _self.data.timeKeeping + 1,
                        timeKeepingText: tools.timeFormat(_self.data.timeKeeping + 1)
                    });
                    console.log('计时', _self.data.timeKeeping);
                    // 当超出时间上限时，停止录音
                    if (_self.data.timeKeeping == 60) {
                        clearInterval(timer);
                        _self.setData({
                            isRecord: false,
                            isRecordClick: false,
                            recordEnd: true
                        })
                    }
                }, 1000);
                _self.timer = timer;
            },
            //录音完成回调
            onStop(ret) {
                clearInterval(_self.timer);

                console.log('录音完成onStop', ret);
                console.log('录音时间', _self.data.timeKeeping);
                innerAudioContext.src = ret.tempFilePath
                _self.setData({
                    recordFilePath: ret.tempFilePath,
                })
                recorder.stop();
                //   _self.voiceDuration();
                //录音完成提示震动
                wx.vibrateShort({
                    complete(res) {
                        console.log('录音完成打开震动', res)
                    }
                });
                wx.showLoading({
                    title: '录音处理中'
                })
            },
            //获取评分结果回调
            onScore(ret) {
                wx.hideLoading();
                console.log("录音评分结果onScore", JSON.parse(ret));
                let result = JSON.parse(ret).result;
                app.globalData.result = result;
                if (result) {
                    console.log('得分结果', result);
                    _self.setData({
                        score: result.overall, //录音得分
                        integrity: result.integrity, //完整度
                        rhythm: result.fluency, //原来的节律度改为流畅度
                        pronunciation: result.pronunciation, //发音得分
                        isRecord: false,
                        timeKeeping: 0,
                        timeKeepingText: "00:00",
                        voiceDuration: _self.data.timeKeeping,
                        remain: _self.data.timeKeeping,
                        isRecordClick: false,
                        recordEnd: true,
                    })

                } else { //获取得分失败重录
                    wx.hideLoading();
                    wx.showModal({
                        title: '温馨提示',
                        content: 'Ai老师计算失误',
                        showCancel: false,
                        confirmText: '再录一次',
                        success: (res) => {
                            if (res.confirm) {
                                console.log('用户点击确定');
                                wx.hideLoading();
                                _self.setData({
                                    isRecord: false,
                                    timeKeeping: 0,
                                    timeKeepingText: "00:00",
                                    isRecordClick: false,
                                })
                            } else if (res.cancel) {
                                console.log('用户点击取消')
                            }
                        }
                    })
                }
            },
            //过程发生错误回调，目前有如下情况会触发：1、录音异常中止 2、远程服务器连接异常中止
            onError(ret) {
                wx.hideLoading();
                console.log("录音过程发生错误回调onError", ret);
                recorder.stop();
                switch (ret.errCode) {
                    case 30001:
                        //还未完成录音服务器就返回报错信息
                        _self.onErrorToRecord();
                        break;
                    case 30002:
                        //正在录音时服务器与客户端主动断开，评分服务器出错
                        _self.onErrorToRecord();
                        break;
                    case 30003:
                        //客户端网络中断或者其他异常导致客户端主动与服务器断开连接
                        _self.onErrorToRecord();
                        break;
                    case 30004:
                        //本地录音机出错，执行错误的停止开始录音流程
                        _self.onErrorToRecord();
                        break;
                    default:
                        console.log('error', ret.errMsg)
                }
            },
            fail(ret) {
                console.log("录音接口调用失败fail", ret);
                wx.hideLoading();
                wx.showModal({
                    title: '温馨提示',
                    content: '录音出了小差错，请重新录制',
                    showCancel: false,
                    success: (res) => {
                        if (res.confirm) {
                            console.log('用户点击确定')
                            _self.setData({
                                isRecord: false,
                                isPlaying: false,
                                isRecordPlaying: false,
                                isButtonClick: false,
                                isRecordClick: false,
                                recordEnd: false,
                                timeKeeping: 0,
                                timeKeepingText: "00:00",
                            })
                        }
                    }
                })
                recorder.stop();
            },
        })

    },
    // 完成录音
    recordEnd() {
        console.log("结束录音");
        let _self = this;
        //录音时间过短
        if (_self.data.timeKeeping < 1) {
            console.log("点击间隔过短")
            return
        }
        app.aldstat.sendEvent('练口语-点击暂停');
        recorder.stop({
            success: (ret) => {
                console.log("skegn_stop success", ret)
            },
            fail: (ret) => {
                console.log("skegn_stop fail", ret)
            },
            complete: (ret) => {
                console.log("skegn_stop complete", ret)
            }
        })
        _self.setData({
            isRecord: false,
            isRecordClick: false,
        })
    },
    //录音出错后执行的重录代码
    onErrorToRecord() {
        let _self = this;
        wx.showModal({
            title: '温馨提示',
            content: '录音出了点小差错,请重新录制',
            showCancel: false,
            confirmText: '确定',
            success: (res) => {
                _self.setData({
                    isRecord: false,
                    isRecordClick: false
                })
            },
        })
    },
    getUserInfo(e) {
        console.log(e)
        app.globalData.userInfo = e.detail.userInfo
        this.setData({
            userInfo: e.detail.userInfo,
            hasUserInfo: true
        })
    },
    //播放示例录音
    playExample(e) {
        console.log("播放示例录音")
        let _self = this;
        let srcStr = e.currentTarget.dataset.src;
        if (srcStr.search(/[A-z./\d]*?mp3/) == -1) {
            console.log('示例录音路径不正确或为空')
            return
        }
        if (_self.data.isButtonClick) {
            console.log("已经有按钮被点击，请稍后再点")
            return
        }
        _self.setData({
            isPlaying: true,
            isButtonClick: true
        })
        //1s后释放状态
        setTimeout(function () {
            _self.setData({
                isButtonClick: false
            })
        }, 1000);
        console.log("示例录音地址", e.currentTarget.dataset.src)

        innerAudioContext.src = srcStr;
        //播放示例录音
        innerAudioContext.play();

        innerAudioContext.onEnded((res) => {
            console.log('正常停止播放', res)
            _self.setData({
                isPlaying: false,
                isButtonClick: false
            })
        })

    },
    //播放用户录音
    playRecord() {
        console.log("播放用户录音")
        let _self = this;
        if (_self.data.isButtonClick) {
            console.log("已经有按钮被点击，请稍后再点")
            return
        }
        app.aldstat.sendEvent('练口语-点击试听');
        clearInterval(timer_play);
        let timer_play = setInterval(function () {
            _self.setData({
                playtimeKeeping: _self.data.playtimeKeeping + 1,
                playRecordText: tools.timeFormat(_self.data.playtimeKeeping + 1)
            });
            console.log('计时', _self.data.playtimeKeeping);
            // 录音正常播放完毕
            if (_self.data.playtimeKeeping == _self.data.voiceDuration) {
                clearInterval(timer_play);
                _self.setData({
                    isRecordPlaying: false,
                    playtimeKeeping: 0,
                    playRecordText: "00:00"
                })
            }
        }, 1000);

        _self.timer_play = timer_play;
        _self.setData({
            isRecordPlaying: true,
            isButtonClick: true,
            playtimeKeeping: 0
        })
        //1s后释放状态
        setTimeout(function () {
            _self.setData({
                isButtonClick: false
            })
        }, 1000);
        innerAudioContext.src = _self.data.recordFilePath;
        innerAudioContext.play();

        innerAudioContext.onEnded((res) => {
            console.log('正常停止播放', res)
            _self.setData({
                isRecordPlaying: false,
                playRecordText: "00:00"
            })
        })
    },
    // 播放单词发音
    playWord(e) {
        innerAudioContext.stop();
        let src = e.currentTarget.dataset.audio;
        innerAudioContext.src = src;
        innerAudioContext.play();
        innerAudioContext.onError((res) => {
            console.log(res.errMsg)
            console.log(res.errCode)
        })
        console.log("播放发音地址", src)
    },
    //停止播放用户录音
    stopRecord() {
        console.log("停止用户录音")
        let _self = this;
        clearInterval(_self.timer_play);
        if (_self.data.isButtonClick) {
            console.log("已经有按钮被点击，请稍后再点")
            return
        }
        innerAudioContext.stop();
        _self.setData({
            isRecordPlaying: false,
            isButtonClick: false,
            remain: _self.data.voiceDuration,
            playRecordText: "00:00"
        })
    },
    //停止播放示例录音
    stopExample() {
        console.log("停止示例录音")
        let _self = this;
        if (_self.data.isButtonClick) {
            console.log("已经有按钮被点击，请稍后再点")
            return
        }
        innerAudioContext.stop();
        _self.setData({
            isPlaying: false,
            isButtonClick: false
        })
    },
    //开始学习(上传用户信息等)
    startLearning() {
        let _self = this;
        let dataDic = {
            VID: _self.data.VID,
            OpenId: app.globalData.openId,
            ImgUrl: app.globalData.userInfo.avatarUrl,
            NickName: app.globalData.userInfo.nickName,
            Source: "PK"
        };
        api.methodWechatDailyVoiceStartLearning({
            dataDic,
            success: (res) => {
                console.log('上传用户信息', res);
            },
            fail: (res) => {
                console.log(res);
            },
            complete: (res) => {
                console.log(res.data);
            }
        })

    },

    //评测(上传用户录音及分数等)
    toResult() {
        let _self = this;
        wx.showLoading({
            title: '评分中',
            mask: false,
        })
        app.aldstat.sendEvent('练口语-点击评测');
        let obj = {
            VoiceDuration: _self.data.voiceDuration,
            VoiceText: _self.data.PracticeSentence.SentenceEn,
            UpfileName: _self.data.recordFilePath
        }
        var voiceJson = JSON.stringify(obj); //json转字符串
        let formDic = {
            action: 'SubmitDailyVoiceInfo',
            AppKey: app.globalData.appkey,
            VID: _self.data.VID,
            OpenId: app.globalData.openId,
            Score: _self.data.score,
            VoiceJson: voiceJson,
            Source: "PK"
        };
        console.log('上传数据', formDic)
        const uploadTask = wx.uploadFile({
            url: app.globalData.apiUrl + app.globalData.baseAshx,
            filePath: _self.data.recordFilePath, //that.data.recordFilePath
            name: _self.data.recordFilePath, //that.data.recordFilePath
            header: {
                'content-type': 'multipart/form-data'
            },
            formData: formDic,
            success: function (res) {
                console.log("上传成功返回的数据", res)
                wx.navigateTo({
                    url: `/pages/spokenPackage/pages/result/result?filePath=${_self.data.recordFilePath}&VID=${_self.data.VID}&voiceDuration=${_self.data.voiceDuration}`
                })
            },
            fail: function (err) {
                console.log("上传失败返回的数据", err)
            },
            complete: function (res) {
                wx.hideLoading();
                //上传录音完成后执行回调
                typeof callback == 'function' && callback(res);
            }
        })


    },

    //跳转到口语秀pk页面
    navToPK() {
        wx.navigateToMiniProgram({
            appId: 'wx820493357a58f254',
            envVersion: 'release',
            success: (res) => {
                // 打开成功
            }
        })
    },
    //单词释义
    slideIn(e) {
        let _self = this;
        let reg = /[a-z]+[\-\']?[a-z]*/ig; //匹配单词正则
        let word = e.currentTarget.dataset.word;
        if (word.search(reg) != 1) {
            console.log("点击的是标点符号或数字")
            return
        }
        app.aldstat.sendEvent('练口语-查询单词次数');
        console.log(e)
        _self.setData({
            slideAnimate: true,
            currentWord: e.currentTarget.dataset.id,
            scrollTop: 0
        })
        let dataDic = {
            word: word
        }
        api.methodGetWordDetail({
            dataDic,
            success: (res) => {
                console.log("查询单词成功", res.data)
                if (res.data.status_code != 0) {
                    console.log("暂无此单词")
                    _self.setData({
                        wordResult: null
                    })
                    return
                }
                _self.setData({
                    wordResult: res.data.data
                })
            },
            fail: (res) => {
                console.log("查询单词失败", res);
            },
            complete: (res) => {
                console.log(res.data);
            },
        })

    },

    slideOut() {
        this.setData({
            slideAnimate: false,
            currentWord: null,
        })
    },
    //句子处理
    dispose() {
        let sentence = this.data.sentence;
        let reg = /[a-z]+[\-\']?[a-z]*|[\d.]+|[\?\!\.\,\;\:\—\-]|\d+/ig;  //将句子拆分成数组
        let wordList = sentence.match(reg);
        let length = wordList.length;
        let re = /[\?\!\.\,\;]/;
        for (let i = 0; i < length; i++) {
            if (wordList[i].search(re) != 0) {
                wordList[i] = ' ' + wordList[i]
            }
        };
        this.setData({
            wordList: wordList
        })
    },

    // 加入单词本
    addWord() {
        let _self = this;
        let dataDic = {
            OpenId: app.globalData.openId,
            Word: _self.data.wordResult.content,
            SoundMarkUK: _self.data.wordResult.pronunciations.uk,
            SoundMarkUS: _self.data.wordResult.pronunciations.us,
            audioUK: _self.data.wordResult.audio_addresses.uk[1],
            audioUS: _self.data.wordResult.audio_addresses.us[1],
            definition: _self.data.wordResult.definition,
        }
        app.aldstat.sendEvent('练口语-加入单词本');
        api.methodAddToWordBook({
            dataDic,
            success: (res) => {
                console.log("加入单词本成功", res.data)
                wx.showToast({
                    title: '加入成功',
                    icon: 'success',
                })
            },
            fail: (res) => {
                console.log("查询单词失败", res);
            },
            complete: (res) => {
                console.log(res.data);
            },
        })
    },
    // 点击我的单词本
    aldWordBook() {
        app.aldstat.sendEvent('练口语-点击我的单词本');
    },
    // 点击排行榜
    aldRankList() {
      
        app.aldstat.sendEvent('练口语-点击排行榜');
    },
    // 隐藏新版功能提示
    hiddenMask() {
        this.setData({
            maskTips: true
        })
        wx.setStorage({
            key: "maskTips",
            data: "true"
        })
    },
    onShareAppMessage(res) {
        let _self = this;
        return {
            title: '口语天天练，成就一口地道外语',
            path: `/pages/spokenPackage/pages/spokenPK/spokenPK?VID=${_self.data.VID}`,
          // path: `/${path.spokenPK}?VID=${_self.data.VID}`,
            //path: `/pages/index/index?VID=2`,
            success: (res) => {
                // 转发成功
            },
            fail: (res) => {
                // 转发失败
            }
        }
    }
})
